package com.he.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author HEHUIJUN
 */
public class ApplicationProperty {
    final static Logger LOGGER= LoggerFactory.getLogger(ApplicationProperty.class);
    final static String PROPERTY_DEST="app.properties";
    volatile static  Properties PROPERTIES=null;
    final static Object propertiesLock=new Object();

    /**
     * 初始化配置文件
     * @param destination
     * @return
     * @throws IOException
     */
    private static Properties initialProperty(String destination) throws IOException {
        if(null==PROPERTIES){
            synchronized (propertiesLock){
                if(null==PROPERTIES){
                    InputStream inputStream=ApplicationProperty.class.getClassLoader().getResourceAsStream(destination);
                    Properties properties=new Properties();
                    properties.load(inputStream);
                    inputStream.close();
                    PROPERTIES=properties;
                }
            }
        }
        return PROPERTIES;
    }

    /**
     * 获取配置文件的值
     * @param key
     * @return
     */
    public static String getValueByKey(String key){
        try {
            Properties properties=initialProperty(PROPERTY_DEST);
            String value=properties.getProperty(key);
            if(value==null)throw new IllegalArgumentException();
            LOGGER.debug("加载的key:{}，获得的value:{}",key,value);
            return value;
        }catch (Exception ex){
            LOGGER.error("加载参数出现异常key是：{};",key,ex);
        }
        return null;
    }

    public static String getFileSystemManagerDest(){
        String system=System.getProperty("os.name");
        if(system.toUpperCase().startsWith("WIN")){
            LOGGER.debug("这是一个windows系统");
            return getValueByKey("app.windows.prefix");
        }else{
            LOGGER.debug("这是一个linux系统");
            return getValueByKey("app.linux.prefix");
        }
    }
}
